package com.harmonk.firstscene

import android.app.Application
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.harmonk.firstscene.db.entity.TrafficEvent
import com.harmonk.firstscene.ui.AboutScreen
import com.harmonk.firstscene.ui.HomeScreen
import com.harmonk.firstscene.ui.QuickNoteScreen
import com.harmonk.firstscene.ui.ReportScreen
import com.harmonk.firstscene.ui.RoadScreen
import com.harmonk.firstscene.ui.component.EventDetail
import com.harmonk.firstscene.ui.model.TrafficEventViewModel
import com.harmonk.firstscene.ui.model.TrafficEventViewModelFactory
import com.harmonk.firstscene.ui.theme.FirstSceneTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : ComponentActivity() {

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            FirstSceneTheme(
            ) {
                MainScreen()
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.R)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    modifier: Modifier = Modifier,
) {
    val navController = rememberNavController()
    val coroutineScope = rememberCoroutineScope()
    val context = remember { navController.context }

    // 创建TrafficEventViewModel实例
    val trafficEventViewModel: TrafficEventViewModel = viewModel(
        factory = TrafficEventViewModelFactory(context.applicationContext as Application)
    )

    NavHost(
        navController = navController,
        startDestination = "main",
        modifier = Modifier
            .fillMaxSize()
            .background(color = MaterialTheme.colorScheme.background)
    ) {
        composable("main") {
            var expanded by remember { mutableStateOf(false) }
            Scaffold(
                modifier = modifier
                    .fillMaxSize()
                    .background(color = MaterialTheme.colorScheme.background),
                topBar = {
                    TopAppBar(
                        title = { Text(stringResource(id = R.string.app_name)) },
                        actions = {
                            IconButton(onClick = { expanded = true }) {
                                Icon(
                                    imageVector = Icons.Outlined.Menu,
                                    contentDescription = "菜单"
                                )
                            }
                            DropdownMenu(
                                expanded = expanded,
                                onDismissRequest = { expanded = false }
                            ) {
                                DropdownMenuItem(
                                    text = { Text("道路管理") },
                                    onClick = {
                                        navController.navigate("road")
                                        expanded = false
                                    }
                                )
                                DropdownMenuItem(
                                    text = { Text("快捷记事") },
                                    onClick = {
                                        navController.navigate("quick_note")
                                        expanded = false
                                    }
                                )
/*
                                DropdownMenuItem(
                                    text = { Text("设置") },
                                    onClick = {
                                        navController.navigate("setting")
                                        expanded = false
                                    }
                                )
*/
                                DropdownMenuItem(
                                    text = { Text("关于") },
                                    onClick = {
                                        navController.navigate("about")
                                        expanded = false
                                    }
                                )
                            }
                        },
                    )
                },
                floatingActionButton = {
                    FloatingActionButton(onClick = {
                        navController.navigate("event_detail/-1")
                    }) {
                        Icon(Icons.Filled.Add, contentDescription = "新建记录")
                    }
                }
            ) { innerPadding ->
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding)
                        .background(color = MaterialTheme.colorScheme.background)
                ) {
                    HomeScreen(
                        onEventClick = { event ->
                            navController.navigate("event_detail/${event.eventId}")
                        },
                        onDeleteEvent = { event ->
                            coroutineScope.launch {
                                trafficEventViewModel.deleteTrafficEvent(event)
                            }
                        }
                    )
                }
            }
        }

        composable("event_detail/{eventId}") { backStackEntry ->
            // 获取事件ID参数
            val eventId = backStackEntry.arguments?.getString("eventId")?.toLongOrNull()

            // 如果事件ID为-1，则创建新的事件，并以新事件的ID作为参数跳转到详情页面
            if (eventId == -1L) {
                // 使用LaunchedEffect等待异步操作完成
                LaunchedEffect(Unit) {
                    // 创建新的事件
                    val newId = withContext(Dispatchers.IO) {
                        trafficEventViewModel.insertTrafficEvent(
                            TrafficEvent(
                                timestamp = System.currentTimeMillis(),
                            )
                        )
                    }
                    // 日志输出新创建的事件ID
                    println("New event created with ID: $newId")
                    // 在获取到eventId后执行导航
                    navController.navigate("event_detail/$newId") {
                        popUpTo("main")
                    }
                }
                // 可以在这里显示加载指示器
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Text("创建中...")
                }
            }
            if (eventId != null && eventId != -1L) {
                // 显示加载状态或详情内容
                EventDetail(
                    navController = navController,
                    eventId = eventId,
                    onBackClick = {
                        navController.popBackStack()
                    }
                )
            }
        }

        composable("road") {
            RoadScreen(
                onBackClick = {
                    navController.popBackStack()
                }
            )
        }
        composable("quick_note") {
            QuickNoteScreen(
                onBackClick = { navController.popBackStack() }
            )
        }
/*
        composable("setting") {
            ProfileScreen(
                onBackClick = { navController.popBackStack() },
                context = LocalContext.current
            )
        }
*/

        composable("about") {
            AboutScreen(
                onBackClick = { navController.popBackStack() }
            )
        }

        composable("report/{eventId}") { backStackEntry ->
            // 获取事件ID参数
            val eventId = backStackEntry.arguments?.getString("eventId")?.toLongOrNull() ?: -1L
            if (eventId != -1L) {
                ReportScreen(
                    onBackClick = { navController.popBackStack() },
                    eventId = eventId
                )
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.R)
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    FirstSceneTheme {
        MainScreen()
    }
}